var app = getApp();


var c = 0
function delay_ms(b) {
	c += 1;
	var ss = setTimeout(delay_ms(b), 1000)

	if (c == b) {
		clearTimeout(ss);
		alert("延时了" + b + "秒")
	}
}

// 位合并  和 获取位
function get_wei(str) {
	
}


// 字符串转byte
function stringToBytes(str) {
	var strArray = new Uint8Array(str.length);
	for (var i = 0; i < str.length; i++) {
		strArray[i] = str.charCodeAt(i);
	}
	const array = new Uint8Array(strArray.length)
	strArray.forEach((item, index) => array[index] = item)
	return array;
}

// ArrayBuffer转16进制字符串示例
function ab2hext(buffer) {
	var hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function (bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('');
}
function ab2hext_str(buffer) {
	var hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function (bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	let hexString = hexArr.join('')
	let splitResult = []; // 存放分割结果的数组
	hexString.match(/.{2}/g).forEach((item) => {
			  splitResult.push(item);
		  });
	return splitResult;
}
/**************************************时间格式化处理************************************/
function dateFtt(date) { //author: meizz 
	return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + '-' + date.getHours() + '：' + date.getMinutes() + '：' + date.getSeconds();
}

function GetKey(value, key) {
	if (value.length) {
		for (let i = 0; i < value.length; i++) {
			if (value[i] == key) {
				value = '';
				return true;
			}
		}
	} else {
		return false;
	}
	value = '';
	return false;
}

//分散字节
function fensan_zijie(decimal) {
	
	// let hexString = decimal.toString(16); // 将十进制数值转换为十六进制字符串
	// let highByte = parseInt(hexString[0], 16).toString(); // 获取高位字节并转换为十进制字符串
	// let lowByte = parseInt(hexString[1], 16).toString(); // 获取低位字节并转换为十进制字符串
	// console.log("高字节：" + highByte);
	// console.log("低字节：" + lowByte);
	// return [highByte,lowByte];  //高字节*256+低字节  0x0001  = 0x00 * 256 + 0x01

	let length = 2;
	var bytes = [];
	var i = 0;
	do {
	bytes[i++] = decimal & (0xFF);
	decimal = decimal>>8;
	} while ( i < length )
	return bytes;
}
//获取数据位运算
function hebing_zijie(l_by,h_by) {
	return parseInt(h_by,16) * 256 + parseInt(l_by,16);  //高字节*256+低字节  0x0001  = 0x00 * 256 + 0x01
}
/*
@old_value 原始值
@value 设置值
@start_bit 开始位
@bit_width  位宽度
@return 新的数据
*/
function set_bit(old_value, value, start_bit, bit_width) {
	return (old_value & (~(((1<<bit_width) - 1) << start_bit))) | ((value & ((1<<bit_width) - 1)) << start_bit);
}

function get_bit(value, start_bit, bit_width) {
    return (value >> start_bit) & ((1<<bit_width) - 1);
}

//16进制转字符串
function hexToString(str) {
	var trimedStr = str.trim();
	var rawStr =
		trimedStr.substr(0, 2).toLowerCase() === "0x" ?
			trimedStr.substr(2) :
			trimedStr;
	var len = rawStr.length;
	if (len % 2 !== 0) {
		// alert("Illegal Format ASCII Code!");
		return "";
	}
	var curCharCode;
	var resultStr = [];
	for (var i = 0; i < len; i = i + 2) {
		curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
		resultStr.push(String.fromCharCode(curCharCode));
	}
	return resultStr.join("");
}
function toUtf8(str) {

	var out, i, len, c;

	out = "";

	len = str.length;

	for (i = 0; i < len; i++) {

		c = str.charCodeAt(i);

		if ((c >= 0x0001) && (c <= 0x007F)) {

			out += str.charAt(i);

		} else if (c > 0x07FF) {

			out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));

			out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));

			out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));

		} else {

			out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));

			out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));

		}

	}

	return out;

}
function UpdateCRC16(crcIn, byte) {
	let crc = crcIn;
	let byte_in = byte | 0x100;
	do {
		crc <<= 1;
		byte_in <<= 1;
		if (byte_in & 0x100)
			++crc;
		if (crc & 0x10000)
			crc ^= 0x1021;
	} while (!(byte_in & 0x10000));
	return crc & 0xffff;
}
function CRC16Modbus(data) {
   let new_arr = data.slice(1);//跳过报文头 
   // 这里是我们想要定义的公共方法的逻辑
   let crcValue = 0xFFFF;
     for (let i = 0; i < new_arr.length; i++) {
         crcValue ^= new_arr[i] & 0xFFFF
         for (let j = 0; j < 8; j++) {
             if (crcValue & 0x0001) {
                 crcValue >>= 1
                 crcValue ^= 0xA001
             } else {
                 crcValue >>= 1
             }
         }
     }
   				  
     crcValue = crcValue.toString(16)
     // let crcArr = new Array(2)
     // crcArr[0] = crcValue.substring(2, 4)
     // crcArr[1] = crcValue.substring(0, 2)
	 data.push(parseInt(crcValue.substring(2, 4),16))
	 data.push(parseInt(crcValue.substring(0, 2),16))
   return data;
}
function CRC16(crc_byte) {
	let crc = 0;
	for (let i = 0; i < crc_byte.length; i++) {
		crc = UpdateCRC16(crc, crc_byte[i]);
	}
	crc = UpdateCRC16(crc, 0);
	crc = UpdateCRC16(crc, 0);
	return crc & 0xffff;
}
/*微信app版本比较*/
function versionCompare(ver1, ver2) {
	var version1pre = parseFloat(ver1)
	var version2pre = parseFloat(ver2)
	var version1next = parseInt(ver1.replace(version1pre + ".", ""))
	var version2next = parseInt(ver2.replace(version2pre + ".", ""))
	if (version1pre > version2pre)
		return true
	else if (version1pre < version2pre)
		return false
	else {
		if (version1next > version2next)
			return true
		else
			return false
	}
}

function Rec_data_deal(buf) {
	
	let BUFFERSIZE = 24;
	let buflen = buf.length;
	let count = 0;
	// app.globalData.RxBuffer = new Uint8Array(48);
	

	while (buflen != 0) {
		app.globalData.RxBuffer[app.globalData.Receive_count] = buf[count];
		count++;
		buflen--;
		switch (app.globalData.rx_status) {
			case 0: {
				if (app.globalData.Receive_count > 0) {
						
						
					if ((app.globalData.RxBuffer[app.globalData.Receive_count - 1] == 0xc0 || app.globalData.RxBuffer[app.globalData.Receive_count - 1] == 0xc9) &&
						app.globalData.RxBuffer[app.globalData.Receive_count] != 0) {
						
						
						app.globalData.RxBuffer[0] = app.globalData.RxBuffer[app.globalData.Receive_count - 1];
						app.globalData.RxBuffer[1] = app.globalData.RxBuffer[app.globalData.Receive_count];
						app.globalData.clc_check_code = app.globalData.RxBuffer[0] ^ app.globalData.RxBuffer[1];
						app.globalData.rx_data_len = app.globalData.RxBuffer[1] + 2;
						app.globalData.rx_status = 1;
						app.globalData.Receive_count = 1;
						
					}
				}
			}
				break;
			case 1: {
			
				if (app.globalData.Receive_count < app.globalData.rx_data_len) {
					app.globalData.clc_check_code ^= app.globalData.RxBuffer[app.globalData.Receive_count];
				} else {
					
					//receive data is equal app.globalData.clc_check_code
					if (app.globalData.Receive_count == app.globalData.rx_data_len + 1) {
						if (app.globalData.clc_check_code == app.globalData.RxBuffer[app.globalData.Receive_count - 1] &&
							app.globalData.RxBuffer[app.globalData.Receive_count] == 0x0d) {
								
								
							if (app.globalData.RxBuffer[0] == 0xc0 && app.globalData.RxBuffer[1] == 0x14) {
								
									
								//if (COMPEAR(3, 4, 'Y', 'B'))
								if (app.globalData.RxBuffer[3] == 0x59 && app.globalData.RxBuffer[4] == 0x42
									&& app.globalData.RxBuffer[2] == 0x0d) {
										
										
									app.globalData.success_count++;
									//rx_data_show();
									let value = new Int16Array(1);
									value[0] = app.globalData.RxBuffer[14] << 8 | app.globalData.RxBuffer[15];
									app.globalData.motor_speed = value[0];

									value[0] = (app.globalData.RxBuffer[5] << 8 | app.globalData.RxBuffer[6]);
									if ((app.globalData.show_switch_bit & 0x10) != 0) {
										
										app.globalData.mcu_q_voltage = value[0];
										
										
									} else if ((app.globalData.show_switch_bit & 0x08) != 0) {
										app.globalData.mcu_q_currente = value[0];
									} else {
										app.globalData.mcu_bus_voltage = value[0] / 10;
									}

									value[0] = app.globalData.RxBuffer[7] << 8 | app.globalData.RxBuffer[8];
									if ((app.globalData.show_switch_bit & 0x10) != 0) {
										app.globalData.mcu_d_voltage = value[0];
									} else if ((app.globalData.show_switch_bit & 0x08) != 0) {
										app.globalData.mcu_d_currente = value[0];
									} else {
										app.globalData.mcu_bus_current = value[0] / 10;
									}

									app.globalData.Ext_temperatrue_senser = app.globalData.RxBuffer[17] - 50;
									app.globalData.MCU_temperatrue_senser = app.globalData.RxBuffer[16] - 50;
									app.globalData.MCU_temperatrue_fact = app.globalData.RxBuffer[19];
									app.globalData.MCU_temperatrue_fact |= app.globalData.RxBuffer[18] << 8;
									app.globalData.mixed_flag_status_show = app.globalData.RxBuffer[20];

									app.globalData.error_code = app.globalData.RxBuffer[13];
									app.globalData.error_code |= app.globalData.RxBuffer[12] << 8;
									app.globalData.error_code |= app.globalData.RxBuffer[11] << 16;
									app.globalData.error_code |= app.globalData.RxBuffer[10] << 24;
										
									let temp = app.globalData.RxBuffer[21];
									if (temp == 0) {
										app.globalData.m_mcu_status_value = "IDLE";
									} else if (temp == 1) {
										app.globalData.m_mcu_status_value = "INIT";
									} else if (temp == 2) {
										app.globalData.m_mcu_status_value = "START";
									} else if (temp == 3) {
										app.globalData.m_mcu_status_value = "RUN";
									} else if (temp == 4) {
										app.globalData.m_mcu_status_value = "STOP";
									} else if (temp == 5) {
										app.globalData.m_mcu_status_value = "BRAKE";
									} else if (temp == 6) {
										app.globalData.m_mcu_status_value = "WAIT";
									} else if (temp == 7) {
										app.globalData.m_mcu_status_value = "FAULT";
									}

									//console.log("电压："+app.globalData.mcu_bus_voltage);
									//console.log("电流"+app.globalData.mcu_bus_current);
								} else if (app.globalData.RxBuffer[3] == 0x52
									&& app.globalData.RxBuffer[2] == 0x05) { //'R'==0x52
									app.globalData.success_count++;
									//get_information_flag = TRUE;
									//information_update();
									//m_tab_updatedata_count = 8;
								} else if (app.globalData.RxBuffer[3] == 0x50 && app.globalData.RxBuffer[4] == 0x4e
									&& app.globalData.RxBuffer[2] == 0x0d) {
									app.globalData.write_param_success_flag = true;
								}
								if (app.globalData.RxBuffer[3] == 0xfe && app.globalData.RxBuffer[4] == 0xef
									&& app.globalData.RxBuffer[2] == 0x0d) {
									app.globalData.reset_mcu_success_flag = true;
									
									//如果是自学习状态 从起不用提醒了  可以震动一下
									console.log("重启成功",app.globalData.zhuansu)
									
									
								
										if(app.globalData.zhuansu<=0){
											//重启的命令吗？
											
											
											if(app.globalData.lang  && app.globalData.lang == 1){
												wx.showToast({
													title: 'The controller has been restarted',
													icon: 'none',
													//mask: true,
													duration: 1500
												})
											}else{
												wx.showToast({
													title: '控制器已经重启',
													icon: 'none',
													//mask: true,
													duration: 1500
												})
											}
											
										}
									
									//8、等待控制器重启成功之后，显示自学习完成
									if(app.globalData.zhuansu == 5){
										
										console.log("学习完成777777777",app.globalData.zhuansu)
										app.globalData.zixuexi = 0;
										
										app.globalData.zhuansu = 0;
										uni.hideLoading();
										
										if(app.globalData.lang  && app.globalData.lang == 1){
											wx.showToast({
												title: 'success',
												icon: 'none',
												//mask: true,
												duration: 1500
											})
										}else{
											wx.showToast({
												title: '学习成功',
												icon: 'none',
												//mask: true,
												duration: 1500
											})
										}
										
									}
									// if(app.globalData.zhuansu<=0){
									// 	wx.showToast({
									// 		title: '控制器已经重启',
									// 		icon: 'none',
									// 		//mask: true,
									// 		duration: 1500
									// 	})
									// }
									// //8、等待控制器重启成功之后，显示自学习完成
									// if(app.globalData.zhuansu == 5){
										
									// 	console.log("学习完成777777777",app.globalData.zhuansu)
										
									// 	app.globalData.zhuansu = 0;
									// 	uni.hideLoading();
									// 	wx.showToast({
									// 		title: '自学习完成',
									// 		icon: 'none',
									// 		//mask: true,
									// 		duration: 1500
									// 	})
										
									// }
									
									wx.vibrateLong();
									setTimeout(function () {
										wx.vibrateLong();
									}, 800)
									
								}
							} else if (app.globalData.RxBuffer[0] == 0xc9) {
								//app.globalData.success_count++;
								//console.log(app.globalData.success_count);
							} else { }
							//console.log(app.globalData.success_count);
						} else {
							app.globalData.error_count++;
							//console.log(app.globalData.error_count);
						}
						app.globalData.rx_status = 0;
						app.globalData.Receive_count = BUFFERSIZE * 2;
					}
				}
			}
				break;
			default: {
				app.globalData.rx_status = 0;
				app.globalData.Receive_count = BUFFERSIZE * 2;
			}
				break;
		}
		
		if (app.globalData.Receive_count < (BUFFERSIZE * 2 - 1)) {
			app.globalData.Receive_count++;
		} else {
			app.globalData.Receive_count = 0;
			app.globalData.rx_status = 0;
		}
		app.globalData.Receive_time_out = 0;
	}
}
function Base64toArrayBuffer(base64Data) {
	const padding = '='.repeat((4 - base64Data.length % 4) % 4);
	const base64 = (base64Data + padding)
		.replace(/\-/g, '+')
		.replace(/_/g, '/');

	const rawData = window.atob(base64);
	const outputArray = new Uint8Array(rawData.length);

	for (let i = 0; i < rawData.length; ++i) {
		outputArray[i] = rawData.charCodeAt(i);
	}
	return outputArray;
}
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
	var hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function (bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('');
}
module.exports = {
	CRC16Modbus:CRC16Modbus,
	stringToBytes: stringToBytes,
	ab2hext: ab2hext,
	ab2hext_str: ab2hext_str,
	hexToString: hexToString,
	CRC16: CRC16,
	GetKey: GetKey,
	Rec_data_deal: Rec_data_deal,
	delay_ms: delay_ms,
	dateFtt: dateFtt,
	toUtf8: toUtf8,
	versionCompare: versionCompare,
	Base64toArrayBuffer: Base64toArrayBuffer,
	ab2hex: ab2hex,
	get_bit:get_bit,
	set_bit:set_bit,
	hebing_zijie:hebing_zijie,
	fensan_zijie:fensan_zijie
}